import React from "react";
import {
  View,
  StyleSheet,
  Alert,
  Vibration,
  Platform,
  Linking,
  Text,
  TouchableOpacity,
} from "react-native";
import TopNavBar from "components/TopNavBar";
import QRScannerView from "components/QRScannerView";
// import Loading from "components/Loading";
import { getStatusBarHeight } from "utils/adaptation";
import ImagePicker from "react-native-image-picker";
import LocalBarcodeRecognizer from "react-native-local-barcode-recognizer";
import { RNReload } from "components/Reload";

const nav = getStatusBarHeight();

export default class ScannerScreen extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      show: true,
      // loading: false,
    };
  }

  componentDidMount() {
    const { navigation } = this.props;
    this.didFocusListener = navigation.addListener("didFocus", () =>
      this.setState({ show: true })
    );
  }

  componentWillUnmount() {
    this.setState({
      show: false,
    });
  }

  barcodeReceived = e => {
    this.setState({
      show: false,
    });

    if (e) {
      // this.setState({ loading: true });
      Vibration.vibrate([0, 500], false);
      const result = e.data;
      const { navigation } = this.props;
      // /(http|https):\/\/([\w.]+\/?)\S*/
      const reg = new RegExp(/(http|https):\/\/([\w.]+\/?)\S*/);
      const reg2 = new RegExp(/(rnapp):\/\/([\w.]+\/?)\S*/);
      if (reg.test(result)) {
        // navigation.navigate("webviewurl", { url: result });
        // openBrowser
        this.localUpdateVersion(result);
      } else if (reg2.test(result)) {
        // rnapp://home/id?
        const newText = result.replace(new RegExp(["rnapp://"], "ig"), "");
        // const keyArr = newText.split("/").filter(k => k);
        navigation.navigate(newText);
      } else {
        navigation.navigate("SearchDetail", { content: result });
      }
    } else {
      // this.setState({ loading: false });

      Alert.alert(
        `${global.lang.home.notice}`,
        `${global.lang.home.scanerror}`,
        [
          {
            text: `${global.lang.home.confirm}`,
            onPress: () => {
              this.setState({
                show: true,
              });
            },
          },
        ],
        { cancelable: false }
      );
    }
  };

  localUpdateVersion = url => {
    if (
      Platform.OS === "android" &&
      typeof RNReload.openBrowser === "function"
    ) {
      RNReload.openBrowser(url);
    } else if (Platform.OS === "ios") {
      Linking.openURL(url);
    }
  };

  openPhoto = () => {
    const options = {
      quality: 1.0,
      storageOptions: {
        skipBackup: true,
        path: "images",
      },
    };

    ImagePicker.launchImageLibrary(options, response => {
      if (response.didCancel) {
        // console.log("User cancelled image picker");
      } else if (response.error) {
        // console.log("ImagePicker Error: ", response.error);
      } else {
        this.recoginze(response.data);
      }
    });
  };

  recoginze = async imageBase64 => {
    // Here is the demoe
    // console.log(imageBase64);
    const result = await LocalBarcodeRecognizer.decode(
      imageBase64.replace("data:image/jpeg;base64,", ""),
      { codeTypes: ["ean13", "qr"] }
    );
    if (result) {
      const { navigation } = this.props;
      // /(http|https):\/\/([\w.]+\/?)\S*/
      const reg = new RegExp(/(http|https):\/\/([\w.]+\/?)\S*/);
      const reg2 = new RegExp(/(rnapp):\/\/([\w.]+\/?)\S*/);
      if (reg.test(result)) {
        // navigation.navigate("webviewurl", { url: result });
        // openBrowser
        this.localUpdateVersion(result);
      } else if (reg2.test(result)) {
        // rnapp://home/id?
        const newText = result.replace(new RegExp(["rnapp://"], "ig"), "");
        // const keyArr = newText.split("/").filter(k => k);
        navigation.navigate(newText);
      } else {
        navigation.navigate("SearchDetail", { content: result });
      }
    }
  };

  right = () => {
    return (
      <View style={styles.right}>
        <TouchableOpacity
          onPress={() => {
            this.openPhoto();
          }}
          style={{ marginRight: 10 }}
        >
          <Text>相册</Text>
        </TouchableOpacity>
      </View>
    );
  };

  render() {
    const { navigation } = this.props;
    const { show } = this.state;
    return (
      <View style={styles.container}>
        <View style={styles.header}>
          <TopNavBar
            midText={global.lang.home.scantitle}
            rightText={this.right()}
            navigation={navigation}
          />
        </View>

        {show && (
          <QRScannerView
            hintText={global.lang.home.scanloading}
            hintTextStyle={{ color: "#fff", fontSize: 18 }}
            maskColor="rgba(0,0,0,0.3)"
            scanBarAnimateTime={3000}
            onScanResult={this.barcodeReceived}
            rectStyle={styles.rectStyle}
            cornerStyle={styles.cornerStyle}
            scanBarStyle={{ backgroundColor: "#48A1FF" }}
          />
        )}
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#FFF",
  },
  header: {
    paddingTop: nav,
  },
  cornerStyle: {
    borderColor: "#48A1FF",
    height: 16,
    width: 16,
    borderWidth: 3,
  },

  rectStyle: {
    borderColor: "#00000080",
    borderWidth: 0.5,
    height: 244,
    width: 244,
  },
});
